package com.xjk.encryp;

import com.xjk.string.StringUtils;

import java.util.Arrays;
import java.util.Map;

public class SignUtil{

    /** MD5签名方式 */
    public static final String SIGN_METHOD_MD5 = "md5";

    /** sha签名方式 */
    public static final String TYPE_SHA = "sha";

    public static String makeSign(Map<String, String> params,String body,String secret,String signMethod) throws Exception{
        return makeSign(secret, params, body + secret, "", "", signMethod);
    }

    public static String makeSign(String start,Map<String, String> paramMap,String end,String flg,String split,String signMethod) throws Exception{
        // 第一步:检查参数是否已经排序
        String[] keys = paramMap.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(start);
        for (int i = 0; i < keys.length; i++){
            String value = paramMap.get(keys[i]);
            if (StringUtils.areNotEmpty(keys[i], value)){
                if (i == keys.length - 1){
                    query.append(keys[i]).append(flg).append(value);
                }else{
                    query.append(keys[i]).append(flg).append(value).append(split);
                }
            }
        }
        query.append(end);
        // 第三步：生产成签名
        byte[] bytes;
        if (SignUtil.TYPE_SHA.equals(signMethod)){
            bytes = ShaEncrypt.encryptSha256(query.toString());
        }else{
            bytes = MD5Encrypt.encryptMD5(query.toString());
        }
        // 第四步：把二进制转化为大写的十六进制
        return byte2hex(bytes);
    }

    /**
     * 把字节流转换为十六进制表示方式。
     */
    public static String byte2hex(byte[] bytes){
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++){
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1){
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
